package com.trailwalker.traceability.util;

import com.trailwalker.JavaUtils.file.FileUtils;
import com.trailwalker.JavaUtils.log.LogUtils;
import com.trailwalker.javafx.utils.thread.ThreadUtils;
import io.reactivex.functions.Consumer;
import javafx.embed.swing.SwingFXUtils;
import javafx.scene.image.Image;
import javafx.scene.image.WritableImage;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author Trailwalker
 * @create 2021-11-13 20:36
 */
public class ImageUtils {

    private static final String TAG = ImageUtils.class.getSimpleName();

    public static void getImageByUrl(String imageUrl, Consumer<Image> consumer) {
        ThreadUtils.runOnChildThread(new Runnable() {
            @Override
            public void run() {
                try {
                    BufferedImage bufferedImage = ImageIO.read(new URL(imageUrl));
                    if (bufferedImage != null) {
                        WritableImage writableImage = SwingFXUtils.toFXImage(bufferedImage, null);
                        if (consumer != null) {
                            ThreadUtils.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    try {
                                        consumer.accept(writableImage);
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        LogUtils.logE(e);
                                    }
                                }
                            });
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    LogUtils.logE(e);
                }
            }
        });
    }

//    public static void getImageByUrl(String imageUrl, Consumer<Image> consumer) {
//        String fileNameWithFormat = imageUrl.substring(imageUrl.lastIndexOf("/") + 1);
//        if (fileNameWithFormat.contains("\\")) {
//            fileNameWithFormat = imageUrl.substring(imageUrl.lastIndexOf("\\") + 1);
//        }
//        String fileNameWithoutFormat = fileNameWithFormat.substring(0, fileNameWithFormat.lastIndexOf("."));
//        String fileFormat = fileNameWithFormat.substring(fileNameWithFormat.lastIndexOf("."));
//        String fileName = fileNameWithoutFormat + "_" + System.currentTimeMillis() + fileFormat;
//        String savePath = FileUtils.getProjectDir() + File.separator + "temp" + File.separator + "images";
//        ThreadUtils.runOnChildThread(new Runnable() {
//            @Override
//            public void run() {
//                File tempImageFile = null;
//                try {
//                    tempImageFile = downloadFromUrl(imageUrl, fileName, savePath);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//                if (tempImageFile != null) {
//                    try {
//                        BufferedImage bufferedImage = ImageIO.read(tempImageFile);
//                        WritableImage writableImage = SwingFXUtils.toFXImage(bufferedImage, null);
//                        if (consumer != null) {
//                            ThreadUtils.runOnUiThread(new Runnable() {
//                                @Override
//                                public void run() {
//                                    try {
//                                        consumer.accept(writableImage);
//                                    } catch (Exception e) {
//                                        e.printStackTrace();
//                                    }
//                                }
//                            });
//                        }
//                    } catch (IOException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        });
//
//    }

    public static File downloadFromUrl(String imageUrl, String fileName, String savePath) throws IOException {
        URL url = new URL(imageUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //设置超时间为3秒
        conn.setConnectTimeout(3 * 1000);
        //防止屏蔽程序抓取而返回403错误
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");

        //得到输入流
        InputStream inputStream = conn.getInputStream();
        //获取自己数组
        byte[] getData = readInputStream(inputStream);

        //文件保存位置
        File saveDir = new File(savePath);
        if (!saveDir.exists()) {
            saveDir.mkdirs();
        }
        File file = new File(savePath + File.separator + fileName);
        FileOutputStream fos = new FileOutputStream(file);
        fos.write(getData);
        fos.close();
        inputStream.close();
        LogUtils.log(TAG, "info:" + url + " download success");
        return file;
    }

    private static byte[] readInputStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        while ((len = inputStream.read(buffer)) != -1) {
            bos.write(buffer, 0, len);
        }
        bos.close();
        return bos.toByteArray();
    }

}
